/**
 * 
 */
package edu.arizona.bio5.onto.decomposition;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;

import uk.ac.manchester.cs.owlapi.modularity.ModuleType;
import edu.arizona.bio5.onto.util.OntologyIterator;
import edu.arizona.bio5.onto.util.OntologyUtils;

/**
 * Evaluates atomic decomposition one a set of ontologies
 * 
 * @author Pavel Klinov
 *
 */
public class ADEvaluator {
	
	private static final String BIOPORTAL_FOLDER = "eval/onto/bioportal";
	private static final String TONES_FOLDER = "eval/onto/tones";
	private static final String CSV_FILE = "eval/onto/tones/tones_ad_eval.csv"; 
	private static final String AD_FOLDER = "eval/onto/tones/atoms";
	static final ModuleType MODULE_TYPE = ModuleType.BOT;
	
	private static ADAlgorithm m_adAlgo = new ChiaraDecompositionAlgorithm(MODULE_TYPE);
	
	
	public static void main(String[] args) throws Exception {
		
		OntologyIterator iter = new OntologyIterator(BIOPORTAL_FOLDER);
		File csvFile = new File(CSV_FILE);
		
		if (csvFile.exists()) {
			
			csvFile.delete();
		}
			
		csvFile.createNewFile();
		
		BufferedWriter writer = new BufferedWriter(new FileWriter(csvFile));
		
		while (iter.hasNext()) {
			
			OWLOntology ontology = iter.next();
			OWLOntologyManager mgr = iter.getCurrentManager();
			
			if (ontology != null) {
				//Remove ABox, etc.
				OntologyUtils.prepareForSyntacticModularity(ontology, mgr);		
				
				mgr.saveOntology(ontology);
				System.out.println(ontology.getLogicalAxiomCount() + " logical axioms. ");
				//Write ontology data
				writer.write(iter.getCurrentOntologyFile() + ",");
				writer.write(ontology.getLogicalAxiomCount() + ",");
				//Skip too big ontologies
				if (ontology.getLogicalAxiomCount() > 15000) {
					
					System.out.println("Too big, skipping");
					writer.newLine();
					
					continue;
				}
				//Decompose
				System.out.print("Decomposing... ");
				
				long ts = System.currentTimeMillis();
				
				AtomicDecomposition ad = null;
				
				try {
					
					ad = m_adAlgo.decompose(mgr, ontology);
					
				} catch (Exception e) {
					
					writer.write("Exception");
					writer.newLine();
					continue;
				}
				
				ts = System.currentTimeMillis() - ts;
				
				System.out.println("Decomposition done in " + ts + " ms");
				//Writing the AD stats
				writer.write(ad.stats().toCommaSeparatedString());
				//Time
				writer.write("," + ts);
				writer.newLine();
				
				writer.flush();
			}
		}
		
		writer.close();
	}

}
